package com.eatme.leetcode.problems;

import com.eatme.core.tree.segmenttree.SegmentTree;

/**
 * 307. 区域和检索 - 数组可修改 - range-sum-query-mutable
 */
class NumArray307 {

    private SegmentTree<Integer> segmentTree;

    public NumArray307(int[] nums) {
        if (nums.length>0) {
            Integer[] data = new Integer[nums.length];
            for (int i = 0; i < nums.length; i++)
                data[i] =nums[i];
            segmentTree = new SegmentTree<>(data,(a, b)-> a+b);

        }
    }

    public void update(int index, int val) {
        if (segmentTree==null)
            throw  new IllegalArgumentException("Segment Tree is null");
        segmentTree.set(index,val);

    }

    public int sumRange(int i,int j) {
        if (segmentTree==null)
            throw  new IllegalArgumentException("Segment Tree is null");
        return segmentTree.query(i,j);
    }

    public static void main(String[] args) {

        NumArray307 numArray = new NumArray307(new int[]{1, 3, 5});
        System.out.println(numArray.sumRange(0, 2));; // 返回 1 + 3 + 5 = 9
        numArray.update(1, 2);   // nums = [1,2,5]
        System.out.println(numArray.sumRange(0, 2)); // 返回 1 + 2 + 5 = 8
    }
}
